namespace NFreeMarker.Core
{
    /// <summary>
    /// Representation of the compile-time Escape directive.
    /// </summary>
    public class EscapeBlock : TemplateElement // NOTE: Was internal
    {
        private readonly string _variable;
        private readonly Expression _expr;
        private Expression _escapedExpr;

        internal EscapeBlock(string variable, Expression expr, Expression escapedExpr)
        {
            _variable = variable;
            _expr = expr;
            _escapedExpr = escapedExpr;
        }

        internal void SetContent(TemplateElement nestedBlock)
        {
            NestedBlock = nestedBlock;
            // We don't need it anymore at this point
            _escapedExpr = null;
        }

        internal override void Accept(Environment env)
        {
            if (NestedBlock != null)
            {
                env.Visit(NestedBlock);
            }
        }

        internal Expression DoEscape(Expression subst)
        {
            return _escapedExpr.DeepClone(_variable, subst);
        }

        public override string GetDescription()
        {
            return "escape " + _variable + " as " + _expr;
        }

        public override string GetCanonicalForm()
        {
            return "<#escape "
                   + _variable
                   + " as "
                   + _expr.GetCanonicalForm()
                   + ">"
                   + NestedBlock.GetCanonicalForm()
                   + "</#escape>";
        }
    }
}